<template>
    <el-dialog
        v-dialogDrag
        :title="dialogType == 1 ? '新增' : '修改'"
        :close-on-click-modal="false"
        :visible.sync="visible"
        @close="handleClose"
        :center="true"
    >
        <!-- 回车监听 @keyup.enter.native="dataFormSubmit()" -->
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
            <el-form-item label="帐号">
                <el-input v-model="dataForm.userId" placeholder="请输入账号" clearable></el-input>
            </el-form-item>

            <el-form-item label="密码">
                <el-input v-model="dataForm.userPwd" placeholder="不填写则不修改密码" show-password></el-input>
            </el-form-item>

            <el-form-item label="所属部门">
                <el-select v-model="baseName" placeholder="请选择" style="width: 100%" :disabled="baseNameSelectedDis">
                    <el-option v-for="(item, index) in baseNameptions" :key="index" :label="item.baseName" :value="item.baseId">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
                <el-input
                    v-model="dataForm.phone"
                    placeholder="请输入手机号"
                    clearable
                    oninput="value=value.replace(/[^\d]/g,'')"
                    maxlength="11"
                ></el-input>
            </el-form-item>

            <el-form-item label="选择角色" prop="roleType">
                <el-select v-model="roleTypeName" placeholder="请选择" style="width: 100%">
                    <el-option v-for="(item, index) in roleOptions" :key="index" :label="item.rolename" :value="item.roleId"> </el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import API from '@/api';
import cloneDeep from 'lodash/cloneDeep';
import { commercialUserType, userType, checkPhoneNumber } from '../../utils/util';
export default {
    filters: {
        userTypeTranslate(val) {
            return userType(val);
        },
        commercialype(val) {
            return commercialUserType(val);
        }
    },
    data() {
        return {
            baseName: '',
            baseNameSelectedDis: false,
            baseNameptions: [
                { baseId: 1, baseName: '市场部', selected: true },
                { baseId: 2, baseName: '风控部', selected: false },
                { baseId: 3, baseName: '科技部', selected: false },
                { baseId: 4, baseName: '交易部', selected: false }
            ],
            roleTypeName: '',
            roleOptions: [],
            visible: false,
            dataForm: {
                roleType: ''
            },
            dataRule: {},
            btnLoading: false,
            dialogType: 1
        };
    },

    methods: {
        handleClose() {
            this.dataForm = {};
            this.$refs['dataForm'].resetFields();
        },

        init(item, type) {
            this.visible = true;

            this.dialogType = type;
            this.getList(item);
            if (item && type == 2) {
                console.log('获取的item数据：', item);
                this.dataForm = item;

                //部门下拉 处理
                this.dataForm.baseName = item.baseName;
                this.baseName = item.baseName;
            } else {
                //部门下拉 默认
                for (var i = 0; i < this.baseNameptions.length; i++) {
                    //配置 下拉框默认选中
                    if (this.baseNameptions[i].selected) {
                        this.dataForm.baseName = this.baseNameptions[i].baseId;
                        this.baseName = this.baseNameptions[i].baseId;
                    }
                }
            }
        },
        getBaseNameptions(parm, name) {
            //选择之后，name为代码id
            for (var i = 0; i < this.baseNameptions.length; i++) {
                if (this.baseNameptions[i].baseId === name) {
                    this.dataForm.baseId = this.baseNameptions[i].baseId;
                    parm.baseId = this.baseNameptions[i].baseId;

                    this.dataForm.baseName = this.baseNameptions[i].baseName;
                    parm.baseName = this.baseNameptions[i].baseName;
                }
            }
        },

        getList(item) {
            //选择角色
            var data = {};
            API.role.getFlowSelectRoleList(data).then((res) => {
                this.roleOptions = res.result;

                if (this.dialogType == 2) {
                    //编辑时 角色取列表数据
                    if (item.roles != null && item.roles.length > 0) {
                        this.dataForm.roleType = item.roles[0].roleId;
                        this.roleTypeName = item.roles[0].rolename;
                    }
                } else {
                    //新增时 角色默认第一个
                    if (this.roleOptions.length > 0) {
                        this.dataForm.roleType = this.roleOptions[0].roleId;
                        this.roleTypeName = this.roleOptions[0].rolename;
                    }
                }
            });
        },

        getType(name) {
            if (this.isChinese(name)) {
                //全是中文，代表用户没有选择，为默认值，或者
                for (var i = 0; i < this.roleOptions.length; i++) {
                    if (this.roleOptions[i].rolename === name) {
                        this.dataForm.roleType = this.roleOptions[i].roleId;
                        return this.roleOptions[i].roleId;
                    }
                }
            } else {
                //选择之后，name为代码id
                for (var i = 0; i < this.roleOptions.length; i++) {
                    if (this.roleOptions[i].roleId === name) {
                        this.dataForm.roleType = this.roleOptions[i].roleId;
                        return this.roleOptions[i].roleId;
                    }
                }
            }
        },

        //是否全是 中文
        isChinese(temp) {
            var re = /[^\u4e00-\u9fa5]/;
            if (re.test(temp)) return false;
            return true;
        },

        // 表单提交
        dataFormSubmit() {
            console.log(this.dataForm);
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    var parm = {
                        userId: this.dataForm.userId, //账号
                        phone: this.dataForm.phone, //手机号
                        roleId: this.getType(this.roleTypeName) //选择角色
                    };

                    //密码处理 (不等于空才传递参数)
                    if (this.dataForm.userPwd != '' && this.dataForm.userPwd != null) {
                        parm.userPwd = this.dataForm.userPwd; //密码
                    }

                    this.getBaseNameptions(parm, this.baseName); //部门处理
                    console.log('传递的参数：', parm);

                    if (this.dialogType == 2) {
                        //编辑

                        // 1. 修改 角色
                        var parmRoles = {
                            roleIds: [this.getType(this.roleTypeName)],
                            userId: this.dataForm.userId
                        };
                        var tickRoles = API.role.editUserRoles(parmRoles);
                        this.btnLoading = true;
                        tickRoles.then((data) => {
                            if (data.code == '0000') {
                                //2.修改 账号信息
                                this.update(parm);
                            }
                        });
                    } else {
                        //新增
                        parm.userType = 'PERSON'; //默认个人
                        parm.merchantType = 'LOAD_FLOW'; //商户类型 管理员添加的默认（ "LOAD_FLOW", "助农贷款审核" ）
                        var tick = API.menu.adminAddAccount(parm);
                        tick.then((data) => {
                            if (data.code == '0000') {
                                this.$message({
                                    message: `新增成功`,
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false;
                                        this.$emit('refreshDataList');
                                    }
                                });
                            }
                            this.btnLoading = false;
                        });
                    }
                }
            });
        },
        update(parm) {
            var tick = API.menu.editAccount(parm);
            tick.then((data) => {
                if (data.code == '0000') {
                    this.$message({
                        message: `修改成功`,
                        type: 'success',
                        duration: 1500,
                        onClose: () => {
                            this.visible = false;
                            this.$emit('refreshDataList');
                        }
                    });
                }
                this.btnLoading = false;
            });
        }
    }
};
</script>